# Process the test images
import struct
import Image
import scipy
import scipy.misc
import scipy.cluster

NUM_CLUSTERS = 5

from numpy import array

from PIL import Image
from PIL import ImageFilter

def pre_filters(image):
	white = image.filter(ImageFilter.BLUR).filter(ImageFilter.MaxFilter(15))
	grey = image.convert('L')
	width,height = image.size
	impix = image.load()
	whitepix = white.load()
	greypix = grey.load()
	for y in range(height):
		for x in range(width):
			white0 = whitepix[x,y][0]
			if white0 == 0: white0 =0.001
			white1 = whitepix[x,y][1]
			if white1 == 0: white1 =0.001
			white2 = whitepix[x,y][2]
			if white2 == 0: white2 =0.001
			greypix[x,y] = min(255, max(255 * impix[x,y][0] / white0, 255 * impix[x,y][1] / white1, 255 * impix[x,y][2] / white2))
	return grey

def filterFindEdges(im):
	return im.filter(ImageFilter.FIND_EDGES)

# Configuration flags
analysis_1 = 1
analysis_2 = 1
analysis_3 = 1
analysis_4 = 1

def image_background_template(image):
	im1 = image.convert('1')
	# Image edges detected and image converted to black and white to generate the image
	image_pixels = im1.load() # this is not a list, nor is it list()'able
	image_width, image_height = im1.size
	print image_width, " ", image_height
	image_template = Image.new('1', im1.size, 0)
	image_template_pixels = image_template.load()
	# Parse the pixels - NEED TO IMPROVE THIS SECTION
	if analysis_1:
		# First filter up to down
		for x in range(image_width):
			# Finding edges algorithm creates a border around the image (as this is a border)
			# For each parsed pixel we must avoid this border.
			# We will pivotate until we pass it by locating a black pixel
			pivot_y = 0
			cur_pixel = image_pixels[x, pivot_y]
			#print pivot_y, ":",cur_pixel,"\n"
			while(cur_pixel!=0): # While pixel is not black
				pivot_y = pivot_y + 1
				if pivot_y<image_height:
					cur_pixel = image_pixels[x, pivot_y]
					#print pivot_y, ":",cur_pixel,"\n"
				else:
					break
			#print "pixel starts in :", pivot_y
			# If we parsed all the line we stop
			if not pivot_y<image_height:
				#print "Line :",x," is empty"
				continue
			#print "pixel starts in :", pivot_y
			cur_pixel = 0
			while(cur_pixel!=255):
				#print x, " ", pivot_y, " ", image_pixels[x, pivot_y], " ", image_template_pixels[x, pivot_y]
				image_template_pixels[x, pivot_y] = 150 # Set the pixel RED
				pivot_y = pivot_y + 1
				if pivot_y<image_height:
					cur_pixel = image_pixels[x, pivot_y]
				else:
					break
	image_template.save('images/output/find_edges_'+str(i)+'_1.png')
	if analysis_2:
		# First filter down to up
		for x in range(image_width):
			# Finding edges algorithm creates a border around the image (as this is a border)
			# For each parsed pixel we must avoid this border.
			# We will pivotate until we pass it by locating a black pixel
			pivot_y = image_height - 1
			cur_pixel = image_pixels[x, pivot_y]
			#print pivot_y, ":",cur_pixel,"\n"
			while(cur_pixel!=0): # While pixel is not black
				pivot_y = pivot_y - 1
				if pivot_y>0:
					cur_pixel = image_pixels[x, pivot_y]
					#print pivot_y, ":",cur_pixel,"\n"
				else:
					break
			#print "pixel starts in :", pivot_y
			# If we parsed all the line we stop
			if not pivot_y>0:
				#print "Line :",x," is empty"
				continue
			#print "pixel starts in :", pivot_y
			cur_pixel = image_height - 1
			while(cur_pixel!=255):
				#print x, " ", pivot_y, " ", image_pixels[x, pivot_y], " ", image_template_pixels[x, pivot_y]
				image_template_pixels[x, pivot_y] = 150 # Set the pixel RED
				pivot_y = pivot_y - 1
				#print x, " ", pivot_y, " ", image_pixels[x, pivot_y]
				if pivot_y>0:
					cur_pixel = image_pixels[x, pivot_y]
				else:
					break
	image_template.save('images/output/find_edges_'+str(i)+'_2.png')
	if analysis_3:
		# Now filter from left to right
		for y in range(image_height):
			# Finding edges algorithm creates a border around the image (as this is a border)
			# For each parsed pixel we must avoid this border.
			# We will pivotate until we pass it by locating a black pixel
			pivot_x = 0
			cur_pixel = image_pixels[pivot_x, y]
			#print pivot_y, ":",cur_pixel,"\n"
			while(cur_pixel!=0): # While pixel is not black
				pivot_x = pivot_x + 1
				if pivot_x<image_width:
					cur_pixel = image_pixels[pivot_x, y]
					#print pivot_y, ":",cur_pixel,"\n"
				else:
					break
			#print "pixel starts in :", pivot_y
			# If we parsed all the line we stop
			if not pivot_x<image_width:
				#print "Line :",x," is empty"
				continue
			#print "pixel starts in :", pivot_y
			cur_pixel = 0
			while(cur_pixel!=255):
				#print x, " ", pivot_y, " ", image_pixels[x, pivot_y], " ", image_template_pixels[x, pivot_y]
				image_template_pixels[pivot_x, y] = 150 # Set the pixel RED
				pivot_x = pivot_x + 1
				if pivot_x<image_width:
					cur_pixel = image_pixels[pivot_x, y]
				else:
					break
	image_template.save('images/output/find_edges_'+str(i)+'_3.png')
	if analysis_4:
		# Now filter from right to left
		for y in range(image_height):
			# Finding edges algorithm creates a border around the image (as this is a border)
			# For each parsed pixel we must avoid this border.
			# We will pivotate until we pass it by locating a black pixel
			pivot_x = image_width - 1
			cur_pixel = image_pixels[pivot_x, y]
			#print pivot_y, ":",cur_pixel,"\n"
			while(cur_pixel!=0): # While pixel is not black
				pivot_x = pivot_x - 1
				if pivot_x>0:
					cur_pixel = image_pixels[pivot_x, y]
					#print pivot_y, ":",cur_pixel,"\n"
				else:
					break
			#print "pixel starts in :", pivot_y
			# If we parsed all the line we stop
			if not pivot_x>0:
				#print "Line :",x," is empty"
				continue
			#print "pixel starts in :", pivot_y
			cur_pixel = image_width - 1
			while(cur_pixel!=255):
				#print x, " ", pivot_y, " ", image_pixels[x, pivot_y], " ", image_template_pixels[x, pivot_y]
				image_template_pixels[pivot_x, y] = 150 # Set the pixel RED
				pivot_x = pivot_x - 1
				#print x, " ", pivot_y, " ", image_pixels[x, pivot_y]
				if pivot_x>0:
					cur_pixel = image_pixels[pivot_x, y]
				else:
					break
	image_template.save('images/output/find_edges_'+str(i)+'_4.png')
	#for y in range(image_height):
	#im1.putdata(image_pixels)
	return image_template

def process_image(image, position, original_image):
	im_filter = image_background_template(image)
	im_filter.save('images/output/angel_filter_'+str(position)+'.png')
	python_array = []
	image_width, image_height = im_filter.size
	image_pixels = original_image.load()
	filter_pixels = im_filter.load()
	for x in range(image_width):
		for y in range(image_height):
			#print filter_pixels[x,y]
			if filter_pixels[x,y] == 0:
				#print "Accepting ",x," ",y,"\n"
				python_array.append(image_pixels[x,y])
	#ar = scipy.misc.fromimage(im)
	ar = array(python_array)
	#print ar
	#shape = ar.shape
	#print shape
	#ar = ar.reshape(scipy.product(shape[:2]), shape[2])

	print 'finding clusters'
	codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
	print 'cluster centres:\n', codes

	vecs, dist = scipy.cluster.vq.vq(ar, codes)         # assign codes
	counts, bins = scipy.histogram(vecs, len(codes))    # count occurrences
	print counts
	print "#####"
	print bins
	index_max = scipy.argmax(counts)                    # find most frequent
	peak = codes[index_max]
	colour = ''.join(chr(c) for c in peak).encode('hex')
	print 'most frequent is %s (#%s)' % (peak, colour)
	return [peak, colour]


# Create output file
FILE = open("output.html","w")
FILE.writelines("<html><head></head><body><table>")
for i in range(1,101):
	print "Processing image ",str(i)
	im = Image.open(r'images/test_'+str(i)+'.jpg')
	grey =  pre_filters(im)
	grey.save('images/output/pre_filter_'+str(i)+'.png')
	edge_image = filterFindEdges(grey)
	edge_image.save('images/output/find_edges_'+str(i)+'.png')
	peak, colour = process_image(edge_image, i, im)
	FILE.writelines("<tr><td><img src='images/test_"+str(i)+".jpg' height='200px' width='200px' /></td>")
	FILE.writelines("<td><img src='images/output/pre_filter_"+str(i)+".png' height='200px' width='200px' /></td>")
	FILE.writelines("<td><img src='images/output/find_edges_"+str(i)+".png' height='200px' width='200px' /></td>")
	FILE.writelines("<td><img src='images/output/angel_filter_"+str(i)+".png' height='200px' width='200px' /></td>")
	FILE.writelines("<td width='200px' height='200px' style='display:block;background-color:" + colour + "'>&nbsp;&nbsp</td></tr>")
FILE.writelines("</table></body></html>")
FILE.close()

